/*
* yasl-qt (or simply yasl) is a qt-based program for symbian devices
* and intended to manage a shopping list.
* The acronym yasl stands for Yet Another Shopping List.
* 
* Copyright (C) 2011 - Alessandro Orlandi
* 
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


#include "ShoppingList.h"
#include <QMessageBox>
ShoppingList::ShoppingList(QWidget *parent) :
    QListWidget(parent)
{
    bool lListLoadSuccessful = loadShoppingListFromFile();
    if (!lListLoadSuccessful)
        qWarning("Problem loading list from file");

}

ShoppingList::~ShoppingList()
{
   //saves data when destroying the shopping list (hopefully on exit)
    saveShoppingList();
}

bool ShoppingList::loadShoppingListFromFile()
{
    QDir dir = QDir::root();
    bool lDirExists = true;
    if (!dir.cd("Data/ShoppingList"))
    {
        qWarning("Cannot find the \"/Data\" directory");
        return false;
    }

    if (lDirExists)
    {
        dir.cd("Data/ShoppingList");
        QFile file(dir.filePath("list.txt"));
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            qWarning("Can't open file");
            return false;
        }

        while (!file.atEnd()) {
            QByteArray line = file.readLine();
            QString lItemLine(line);
            QStringList lItemData = lItemLine.split("|");
            QString lItemName = lItemData.at(0);
            int lItemTaken = atoi(lItemData.at(1).toStdString().c_str());
            QListWidgetItem *lNewItem = new QListWidgetItem(lItemName);
            QFont lFont(lNewItem->font());

            if (lItemTaken != 0)
            {
                lFont.setStrikeOut(true);
                lNewItem->setFont(lFont);
            }
            QListWidget::addItem(lNewItem);

        }
        return true;
    }
    else
    {
        return false;
    }
}

void ShoppingList::addNewItem(QString pItem)
{

    bool lNewItemNotInList = true;
    int lItemCount = count();
    if (lItemCount>0)
    {
        QListWidgetItem * lItem;
        QString lItemText;

        for (int i=0; i < lItemCount && lNewItemNotInList; i++)
        {
            lItem = item(i);
            lItemText = lItem->text();
            if (lItemText.compare(pItem,Qt::CaseInsensitive) == 0)
            {
                lNewItemNotInList = false;
            }
        }
    }
    if (lNewItemNotInList)
    {
        QListWidgetItem *newItem = new QListWidgetItem(pItem);
        QListWidget::addItem(newItem);
        refreshListView();
    }
}

void ShoppingList::removeSelectedItem(){


    QList<QListWidgetItem*> lSelectedItems = selectedItems();

    if (lSelectedItems.length()>0)
    {
        QMessageBox lConfirmationMsgBox;
        lConfirmationMsgBox.setText("Removing item!");
        lConfirmationMsgBox.setInformativeText("Selected item will be permanently removed from the shopping list.\nAre you sure?");
        lConfirmationMsgBox.setStandardButtons(QMessageBox::No|QMessageBox::Yes);
        lConfirmationMsgBox.setDefaultButton(QMessageBox::No);
        lConfirmationMsgBox.show();
        int lActionConfirmed = lConfirmationMsgBox.exec();


        if (lActionConfirmed == QMessageBox::Yes)
        {
            QListWidgetItem * lItem = lSelectedItems.first();
            if (lItem != NULL )
            {
                QString lItemName = lItem->text();
                QListWidget::removeItemWidget(lItem);
                delete lItem;
                emit sigItemRemoved(lItemName);
            }
        }
    }
}

void ShoppingList::takeSelectedItem(){

    QList<QListWidgetItem*> lSelectedItems = selectedItems();

    if (lSelectedItems.length()>0)
    {
        QListWidgetItem * lItem = lSelectedItems.first();
        if (lItem != NULL )
        {
            QFont lFont(lItem->font());
            lFont.setStrikeOut(true);
            lItem->setFont(lFont);
            refreshListView();
            emit sigItemTaken(lItem->text());
        }
    }
}

void ShoppingList::dropSelectedItem(){

    QList<QListWidgetItem*> lSelectedItems = selectedItems();

    if (lSelectedItems.length()>0)
    {
        QListWidgetItem * lItem = lSelectedItems.first();
        if (lItem != NULL )
        {
            QFont lFont(lItem->font());
            lFont.setStrikeOut(false);
            lItem->setFont(lFont);
            refreshListView();
            emit sigItemDropped(lItem->text());
        }
    }
}




void ShoppingList::removeItemByName(QString pItemToRemove)
{
    QList<QListWidgetItem*> lItems = QListWidget::findItems(pItemToRemove,Qt::MatchCaseSensitive);
    if (lItems.length()>0)
    {
        QString lItemName;
        QListWidgetItem * lItem;
        for (int i=0; i<lItems.length(); i++)
        {
            lItem = lItems.at(i);
            lItemName = lItem->text();
            if (lItemName.compare(pItemToRemove,Qt::CaseSensitive) == 0)
            {
                QListWidget::removeItemWidget(lItem);
                delete lItem;
                emit sigItemRemoved(lItemName);
                return;
            }

        }
    }

}

void ShoppingList::saveShoppingList()
{

    QDir dir = QDir::root();
    bool lDirExists = true;
    if (!dir.cd("Data/ShoppingList"))
    {

        qWarning("Cannot find the \"/Data\" directory");
        lDirExists = dir.mkpath("Data/ShoppingList");
    }

    if (lDirExists)
    {
        dir.cd("Data/ShoppingList");
        QFile file(dir.filePath("list.txt"));
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            qWarning("Can't create file");
            return;
        }
        QTextStream out(&file);
        QListWidgetItem * lItem;
        for (int i=0; i < count() ; i++)
        {
            lItem = item(i);
            QFont lFont(lItem->font());
            out << lItem->text();
            if (lFont.strikeOut())
                out <<  "|1";
            else
                out <<  "|0";
            out << "\n";
        }
    }
}

void ShoppingList::setShowOption(int pShowOption)
{
    mShowOption = pShowOption;
    refreshListView();
}

void ShoppingList::refreshListView(QString)
{
    sortItems();
    int lItemCount = count();
    if (lItemCount>0)
    {
        QListWidgetItem * lItem;
        for (int i=0; i<lItemCount; i++)
        {
            lItem = item(i);
            QFont lFont(lItem->font());
            switch(mShowOption)
            {
            case 0:  /*show ALL*/
                lItem->setHidden(false);
                break;
            case 1:   /*show MISSING only*/
                if(lFont.strikeOut() /*item TAKEN*/)
                    lItem->setHidden(true);
                else
                    lItem->setHidden(false);
                break;

            case 2:  /*show TAKEN only*/
                if(!lFont.strikeOut() /*item to buy*/)
                    lItem->setHidden(true);
                else
                    lItem->setHidden(false);
                break;
            }
        }
    }
}


void ShoppingList::purgeShoppingList()
{
    QStringList lPurgedItemsList;
    int lItemCount = count();
    if (lItemCount > 0)
    {

        QMessageBox lConfirmationMsgBox;
        lConfirmationMsgBox.setText("Purging shopping list");
        lConfirmationMsgBox.setInformativeText("All 'taken' item (striked-out) will be removed from the current shopping list and copied to history for future usage.\nContinue?");
        lConfirmationMsgBox.setStandardButtons(QMessageBox::No|QMessageBox::Yes);
        lConfirmationMsgBox.setDefaultButton(QMessageBox::No);
        lConfirmationMsgBox.show();
        int lActionConfirmed = lConfirmationMsgBox.exec();

        if ( lActionConfirmed != QMessageBox::Yes)
            return;


        QListWidgetItem * lItem;
        QFont lFont;
        for (int i=0; i<lItemCount; i++)
        {
            lItem = item(i);
            lFont = lItem->font();

            if (lFont.strikeOut())
            {
               lPurgedItemsList << lItem->text();
            }
        }

        if (lPurgedItemsList.length()>0)
        {
            for (int i=0; i<lPurgedItemsList.length(); i++)
            {

                removeItemByName(lPurgedItemsList.at(i));
            }
            emit sigListPurged(lPurgedItemsList);
        }

    }
}


